<?php 
/**
* 
*/
class Rest
{
	//用户类
	private $_user;

	//文章类
	private $_article;


	//资源标识
	private $_Uri;


	//版本标识
	private $_version;


	//允许用户请求方法
	private $_allowMethod = ['GET','POST','DELETE','PUT'];

	//允许用户请求资源
	private $_allowResource = ['users','articles'];


	//自定义状态码
	private $_status = [
		200 => 'OK',
		403 => 'For Bidden',
		405 => 'Request Not Found',
		404 => 'Not Found',

	];
	function __construct(User $user,Article $article)
	{
		$this->_user = $user;
		$this->_article = $article;
	}



	//启动方法
	public function run() {

		// print_r($_SERVER);
		try {
			$this->setMethod();
			$this->setResource();
			if($this->requestResource() == 'users'){
				$this->sendUsers();
			} else {
				$this->sendArticles();
			}
		} catch (Exception $e) {
			$this->_json($e->getMessage(),$e->getCode());
		}
		
	}

	//判断用户请求方法是否合法  
	// return string 请求方法
	private function setMethod(){
		$ReuestMethod = $_SERVER['REQUEST_METHOD'];
		if (!in_array($ReuestMethod, $this->_allowMethod)) {
			throw new Exception("请求方法不被允许", 405);
			
		}
		return $ReuestMethod;
	}


	//判断用户请求资源是否合法
	private function setResource(){
		$path = $_SERVER['REDIRECT_URL'];
		$params = explode('/', $path);
		// print_r($params);exit();
		if (!empty($params[3])) {
			$this->_Uri = $params[3];
		}

		$this->_version = $params[1];
		// print_r($params);
		if (!in_array($params['2'], $this->_allowResource)) {
			throw new Exception("请求资源不被允许", 403);
			
		}

	}


	//json格式方法
	private function _json($message,$code){
		if ($code !== 200 && $code !== 1) {
			header('HTTP/1.1 '.$code.' '.$this->_status[$code]);
		}
		header('Content-Type:application/json;charset=utf8');
		print_r(json_encode([$message,$code]));
	}



	//请求资源
	private function requestResource() {
		$path = $_SERVER['REDIRECT_URL'];
		$params = explode('/', $path);
		return $params['2'];
	}



	//用户资源判断
	private function sendUsers() {
		if ($this->setMethod() !== 'POST') {
			throw new Exception("请求方法错误", 405);
			
		}

		if (empty($this->_Uri)) {
			throw new Exception("请求参数缺失", 400);
			
		} elseif ($this->_Uri == 'login') {
			$this->dologin();
		} elseif ($this->_Uri == 'register') {
			$this->doregister();
		} else {
			throw new Exception("请求资源不被允许", 405);
			
		}
	}




	//文章接处理
	private function sendArticles() {


		switch ($this->setMethod()) {
			case 'POST':
				return $this->article_Create();

			case 'DELETE':
				return $this->delArticle();

			case 'PUT':
				return $this->edit();

			case 'GET':

				if ($this->_Uri == 'list') {

					$this->articleList();

				} elseif ($this->_Uri >= 0) {

					$this->articleView();

				} else {
					throw new Exception("请求资源不合法", 405);
					
				}
	
		}





	}



	//文章发表接口

	private function article_Create() {

		session_start();
		// print_r(session_id());exit();
		$data = $this->getBody();
		if (empty($data['title'])) {
			throw new Exception("文章名不能为空", 400);
			
		}

		if (empty($data['content'])) {
			throw new Exception("文章内容不能为空", 400);
			
		}

		if(!$this->islogin($data['token'])){
			throw new Exception("请重新登陆", 403);
			
		}

		$user_id = $_SESSION['userInfo']['id'];

		$return = $this->_article->articleCreate($data['title'],$data['content'],$user_id);
		if (!empty($return)) {
			return _json('文章发表成功',200);
			// throw new Exception("文章发表失败", 405);
			
		} else {
			throw new Exception("文章发表失败", 405);
			
		}
	}


	private function articleList() {

	}



	//登陆验证方法
	//判断用户是否登陆  返回布尔值
	private function islogin($token){
		session_start();
		$sessionId = session_id();
		if ($sessionId != $token) {
			return false;
		}

		return true;
	}



	//文章修改api
	private function edit() {
		
		$data = $this->getBody();
		$token = $data['token'];
		if(!$this->islogin($token)){
			throw new Exception("请重新登陆", 403);
			die;
		}
		// print_r($data['title']);
		// var_dump($_SESSION['userInfo']['id']);
		$return = $this->_article->edit($this->_Uri,$data['title'],$data['content'],(int)$_SESSION['userInfo']['id']);
		// print_r($return);
		$data = [
			'data'=>[
				'user_id'=>$_SESSION['userInfo']['id'],
				'title'=>$return['title'],
				'content'=>$return['content'],
				'create_time'=>$return['create_time'],
			],
			'message'=>'修改成功',
			'code'=>200
		];

		echo json_encode($data);
	}


	private function delArticle() {
		//获取输入流
		$data = $this->getBody();
		if(!$this->islogin($data['token'])){
			throw new Exception("请重新登陆", 403);
			
		}


		$return = $this->_article->delete($this->_Uri,(int)$_SESSION['userInfo']['id']);
		echo json_encode($return);
	}

	//文章查看接口

	private function articleView() {
		if (empty($this->_Uri)) {
			throw new Exception("请求资源不合法", 405);
			
		} 

		$article = $this->_article->view($this->_Uri);
		$data = [
			'data'=>[
				'title'=>$article['title'],
				'content'=>$article['content'],
				'user_id'=>$article['user_id'],
				'create_time'=>$article['create_time']
			],
			'message'=>'查看 成功',
			'code'=>200
		];

		echo json_encode($data);
	}


	//用户注册接口
	private function doregister() {
		$data = $this->getBody();
		// var_dump($data['name']);
		if (empty($data['name'])) {
			throw new Exception("用户名不能为空", 400);
			
		}
		if (empty($data['passwd'])) {
			throw new Exception("用户密码不能为空", 400);
			
		}

		if ($this->_user->register($data['name'],$data['passwd'])) {
			$this->_json('注册成功',200);
		} else{
			throw new Exception("注册失败", 400);
			
		}
	}


	//用户登陆接口
	private function dologin(){
		$data = $this->getBody();
		if (empty($data['name'])) {
			throw new Exception("用户名不能为空", 400);
			
		}
		if (empty($data['passwd'])) {
			throw new Exception("密码不能为空", 400);
			
		}
		$user = $this->_user->login($data['name'],$data['passwd']);
		// print_r($user);die();
		$data = [
			'data'=>[
				'user_id'=>$user['id'],
				'user_name'=>$user['name'],
				'token'=>session_id()
			],
			'message'=>'登陆成功',
			'code'=>200
		];

		echo json_encode($data);
		die;
			
	
	}


	//获取前端传参
	private function getBody() {
		$data = file_get_contents("php://input");
		if (empty($data)) {
			throw new Exception("请求参数错误", 405);
			
		}
		return json_decode($data,true);
	}
}
